package com.wwdx.shiro;

import com.wwdx.model.upms.UpmsUser;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.io.Serializable;

/**
 * 当前登录用户信息,可以在bean中调用获取当前登录用户信息,例如 SessionUser.getUserId()获取当前登录人的userId
 * @author liguoliang
 */
@Data
public class SessionUser implements Serializable{

	/**
	 * 编号
	 */
	private Integer id;
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 账号
	 */
	private String account;

	/**
	 * 商户
	 */
	private String merchant;

	/**
	 * 邮箱
	 */
	private String mail;

	/**
	 * 2.女1.男
	 */
	private Integer sex;

	public SessionUser(UpmsUser user) {
		this.id = user.getUserId();
		this.account = user.getAccount();
		this.name = user.getRealname();
		this.mail = user.getEmail();
		this.sex = user.getSex();
		this.merchant = user.getMerchantId();
	}
	
	private static SessionUser getShiroUser() {
		Subject user = SecurityUtils.getSubject();
		if (user == null) {
			return null;
		}
		SessionUser shiroUser = (SessionUser) user.getPrincipal();
		if (shiroUser == null) {
			return null;
		}
		return shiroUser;
	}

    public static Integer getUserId() {
        SessionUser shiroUser = getShiroUser();
        if (shiroUser == null) {
            return null;
        }
        return shiroUser.getId();
    }

    public static String getUserName() {
        SessionUser shiroUser = getShiroUser();
        if (shiroUser == null) {
            return null;
        }
        return shiroUser.getName();
    }

    public static String getEmail() {
        SessionUser shiroUser = getShiroUser();
        if (shiroUser == null) {
            return null;
        }
        return shiroUser.getMail();
    }

    public static String getMerchantId() {
        SessionUser shiroUser = getShiroUser();
        if (shiroUser == null) {
            return null;
        }
        return shiroUser.getMerchant();
    }

	public static Session getSession() {
		Subject user = SecurityUtils.getSubject();
		if (user == null) {
			return null;
		}
		return user.getSession();
	}
}